package com.biz.service.sys;

import com.alibaba.druid.util.Utils;
import com.biz.model.Hmodel.TSysUser;
import com.biz.model.Hmodel.basic.TGrade;
import com.biz.model.Pmodel.SysUser;
import com.biz.service.base.BaseServiceImpl;
import com.framework.dao.hdao.BaseDaoI;
import com.framework.dao.mdao.DaoSupport;
import com.framework.model.Paging;
import com.framework.utils.StringUtil;
import com.framework.utils.UuidUtil;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by yzljj on 2016/6/23.
 */
@Service("userClientService")
public class SysUserServiceImpl extends BaseServiceImpl<SysUser> implements SysUserServiceI {

    @Autowired
    private BaseDaoI<TSysUser> userDao;
    @Autowired
    private BaseDaoI<TGrade> gradeDao;

    @Resource(name = "daoSupport")
    private DaoSupport dao;

    @Override
    public Paging getSysUserGridPage(Map<String,Object> params)throws Exception {
       // String sql="select * from demo_grid ";
        //String countSql="select count(1) from demo_grid ";
       // SqlFactory factory=new SqlFactory();
      //  System.out.println("AA;"+factory.getSql(sql,params,sqlParams));
       // System.out.println("BB;"+factory.getCountSql(countSql, params));
        Paging paging=dao.findForPaging("sysUserDao.sysUserList",params, "sysUserDao.sysUserCount", params);
        return paging;
    }

    @Override
    public Paging getSysUserGridPage2(Map<String,Object> params)throws Exception {
        Paging paging=dao.findForPaging("sysUserDao.sysUserList2",params, "sysUserDao.sysUserCount2", params);
        return paging;
    }

    @Override
    public Paging getGradeGridPage(Map<String, Object> params)throws Exception{
        Paging paging=dao.findForPaging("sysUserDao.GradeList",params, "sysUserDao.GradeCount", params);
        return paging;
    }

    @Override
    public TGrade getTGradeById(String id)throws Exception{
       return  gradeDao.getById(TGrade.class,id);
    }

    @Override
    public void saveGrade(TGrade tgrade)throws Exception{
        int count =(int)dao.findForObject("sysUserDao.GetGradeCount","");
        tgrade.setGrade(count);
        tgrade.setIsdel((short) 0);
        tgrade.setCreateTime(df.format(new Date()));
        gradeDao.save(tgrade);
    }

    @Override
    public void updateTGrade(TGrade tgrade)throws Exception{

        gradeDao.update(tgrade);
    }

    @Override
    public void deGradeByIds(String ids)throws Exception{

        String [] idArray = ids.split(",");
        if(idArray.length>0)
        {
            String lastId=idArray[idArray.length-1];

            List<TGrade> list=(List<TGrade>)dao.findForList("sysUserDao.GetLastGrades",lastId);
            if(list!=null && list.size()>0)
            {
                for(int i=0;i<list.size();i++)
                {
                    TGrade temp = list.get(i);
                    temp.setGrade(temp.getGrade()-idArray.length);
                    gradeDao.update(temp);
                }
            }
        }
        gradeDao.executeHql(StringUtil.formateString("update TGrade set isdel =1 where id in ({0})", StringUtil.formatSqlIn(ids)));
    }

    @Override
    public Paging getBaseUserGridPage(Map<String,Object> params)throws Exception {
        Paging paging=dao.findForPaging("sysUserDao.baseUserPage",params, "sysUserDao.countBaseUser", params);
        return paging;
    }

    public void updateUserLock(Map<String,Object> params) throws Exception
    {
        dao.update("sysUserDao.updateUserLock", params);
    }

    /**
     * 获取
     *
     * @param user_code
     * @return
     * @throws Exception
     */
    public SysUser getUserByCode(String user_code) throws Exception
    {
        return (SysUser) dao.findForObject("sysUserDao.getUserByCode", user_code);
    }


    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
    @Override
    public String insertUser(SysUser user) {
        TSysUser tuser=new TSysUser();
        BeanUtils.copyProperties(user,tuser, "isdel","createTime", "type","pwd", "sorts");
        tuser.setType(1);
        tuser.setIdentity(Integer.valueOf(user.getIdentity()));
        tuser.setIsdel(0);
        tuser.setPwd(Utils.md5(user.getLogin_name()));
        tuser.setSort(Integer.valueOf(user.getSorts()));

        tuser.setIslock(0);

        tuser.setCreate_time(new Date());
        userDao.save(tuser);
        return tuser.getUser_code();
    }

    @Override
    public void updateUser(SysUser user) {
        TSysUser tuser=userDao.getById(TSysUser.class,user.getId());
        BeanUtils.copyProperties(user,tuser, "isdel","login_name","state","createTime","sex","islock","type","pwd","sorts","identity","identity_code");
       /* if(user.getSpType().equals("sp"))
        {
          //  tuser.setState(user.getState());
        }*/

        userDao.update(tuser);
    }

    @Override
    public void delGridById(String ids) {
        String [] idList=ids.split(",");
        for (String id:idList) {
            TSysUser tuser= userDao.getById(TSysUser.class,id);
            tuser.setIsdel(1);
            userDao.update(tuser);
        }
    }

    @Override
    public List<Map<String, Object>> getAllAppid() throws Exception {
        return (List<Map<String, Object>>) dao.findForList("sysUserDao.getAllAppid",null);
    }

    @Override
    public List<Map<String,Object>> getDutyListByDate(Map<String,Object> param)throws Exception{
        return (List<Map<String, Object>>) dao.findForList("sysUserDao.getDutyListByDate",param);
    }

    @Override
    public void setDutyUser(String dutyUserId,String dutyDateStr,String userId)throws Exception{
        String startDate=dutyDateStr.substring(0, 10);
        String endDate=dutyDateStr.substring(13, 23);
        Integer start=Integer.valueOf(startDate.substring(8,10));
        Integer end=Integer.valueOf(endDate.substring(8,10));

        String tempDate=startDate.substring(0,7);
        Map<String,Object> parmas;
        for(int i=0;i<=(end-start);i++)
        {
            parmas=new HashMap<>();
            String dutyDate=tempDate+"-"+String.valueOf(start+i);
            parmas.put("dutyDate",dutyDate);
            parmas.put("dutyUserId",dutyUserId);
            parmas.put("userId",userId);
            Integer count = (Integer)dao.findForObject("sysUserDao.checkDutyByUserId",parmas);
            if(count==0)
            {
                parmas.put("id", UUID.randomUUID().toString());
                dao.save("sysUserDao.saveDutyByUserId",parmas);
            }
        }

    }

    @Override
    public String getIntroduce() throws Exception {
        return (String)dao.findForObject("sysUserDao.getIntroduce",null);
    }

    @Override
    public void saveIntroduce(String content) throws Exception {
        Map<String,Object> map=new HashedMap();
            //删除旧的
            dao.update("sysUserDao.updateIntroduce",content);
            map.put("id", UuidUtil.get32UUID());
            map.put("content",content);
            dao.save("sysUserDao.insertContent",map);
        }
}
